package stub;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import format.Format;
import format.InvalidFormatException;
import format.TraitFormat;

/**
 * Manage the stub for TraitFormat.<br>
 * Get his data from an Excel file specified in stub.properties.
 * 
 * @author Richard Pula
 *
 */
public class TraitFormatStub {
	
	static private String className;
	static private Map<String, Format> map;
	
	static {
		className = TraitFormat.class.getSimpleName();
		map		  = loadStubMap();
	}
	
	/**
	 * Get the outpout Format from the stub file.<br>
	 * If output correspondig to the input doesn't exist
	 * a F0 Format is return.
	 * 
	 * @param input
	 * @return Format corresponding to the input
	 */
	static public Format getOutput(String input) {
		Format format = map.get(input);
		
		if (format != null) {
			return format;
		}
		else {
			return Format.defaultFormat;
		}
	}
	
	/**
	 * Load the TraitFormatStub from a Excel file specified in stub.properties.
	 * 
	 * @return the Stub Map
	 */
	private static Map<String, Format> loadStubMap() {
		String excelFile = StubPropreties.getFileByClassName(className);
		return getStubFromExcel(excelFile);
	}
	
	/**
	 * Get the Stub from an Excel file.<br>
	 * The first column correponds to the input and the second to the expected Format for this input.
	 * 
	 * @param excelFile The excel file path which contains the Stub
	 * @return the Stub Map
	 */
	static private Map<String, Format> getStubFromExcel(String excelFile) {
		Map<String, Format> stubMap = new HashMap<String, Format>();
		
		try {
		    HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(excelFile));
		    HSSFSheet sheet = wb.getSheetAt(0);
		    HSSFRow row;
		    
			String input;
			Format expected;
			
			String tmp;
			
			Iterator<HSSFRow> rit = sheet.rowIterator();
			rit.next(); // pass the header
			
		    for (; rit.hasNext(); ) {
				row = rit.next();
				
				// input 
				input = row.getCell(0).getRichStringCellValue().getString();
				
				// expected
				tmp = row.getCell(1).getRichStringCellValue().getString();
				expected = Format.getFormatByString(tmp);
				
				stubMap.put(input, expected);
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (InvalidFormatException e) {
			e.printStackTrace();
		}
		
		return stubMap;
	}	
	
}
